/*
* @author psj
*/

//컨트롤
function Letter_View() {
    this.letterView = null;
    this.letterComm = null;

    this.q_seq = null;
    this.q_type = null;
    this.q_ynSaved = null;
}

Letter_View.prototype = {
    onPageShow : function() {

        $("a").attr("href", "");
        this._init();
    },
    _init : function() {

        this._preload();
        this.letterView = new letterView_View();
        this.letterComm = new letterView_Comm();

        this._start();
        this._bind();
    },
    _preload : function() {
        this.q_seq = document.globalObj.LETTER_DATA.q_seq;
        this.q_type = document.globalObj.LETTER_DATA.q_type;
        this.q_ynSaved = document.globalObj.LETTER_DATA.q_ynSaved;

        if(!this.q_seq) {
            alert("비정상적 접근입니다.");
            $.mobile.changePage("letter.html");
            return;
        }
    },
    _bind : function() {
        var _this = this;
        
        this.letterView.HTMLDom["$answer"].on('click', function() {
            _this.goWritePage(_this.letterView.infoData["회원정보"]["유저정보"]);
        });
        this.letterView.HTMLDom['$save'].on('click', function() {
            _this.noteSave();
        });
        this.letterView.HTMLDom['$delete'].on('click', function() {
           _this.noteDelete();
        });
        $(this.letterComm).bind('finishNoteInfo', function(event) {
            var _thisData = _this.letterComm.getNoteData();
            _this.letterComm.getUserInfo(_thisData["회원정보"]["아이디"]);
            _this.letterView.setInfo(_thisData);
            console.log(_thisData)
        });
        $(this.letterComm).bind('finishUserInfo', function(event) {
            var _thisData = _this.letterComm.getUserData();
            _this.letterView.setMemberInfo(_thisData);
            //console.log(_thisData)
        });
        $(this.letterComm).bind('finishSaveLetter', function(event) {
            var _thisData = _this.letterComm.getSaveInfoData();
            _this.letterView.finishNoteSave(_thisData);
            //console.log(_thisData)
        });
        $(this.letterComm).bind('finishDeleteLetter', function(event) {
            var _thisData = _this.letterComm.getDeleteInfoData();
            _this.letterView.finishNoteDelete(_thisData);
            //console.log(_thisData)
        });
    },
    _start : function(data) {
        this.letterView.spinStart();
        this.letterComm.getNoteInfo({
            "송수신코드" : this.q_type,
            "코드" : this.q_seq,
            "보관여부" : this.q_ynSaved
        });
    }
    , goWritePage : function(userInfo){
        document.globalObj.PROFILE_DATA.userId = userInfo["아이디"];
        document.globalObj.PROFILE_DATA.nickName = userInfo["닉네임"];
        $.mobile.changePage("letter_write.html");
    }
    , noteSave: function(){
        this.letterView.spinStart();
        this.letterComm.noteSave({
            "송수신코드": this.q_type
            , "코드": this.q_seq
        });
    }
    , noteDelete : function(){
        if(!confirm("삭제하시겠습니까?")) return;
        
       this.letterView.spinStart();
        var options = {
            "코드": this.q_seq
        }
        
        this.letterComm.noteDelete({
            "송수신코드": this.q_type
            , "코드": this.q_seq
            , "보관여부": this.q_ynSaved
        });       
    }
}
/*
 * data
 */
function letterView_Comm() {
    this.noteInfo = {};
    this.userInfo = {};
    this.saveDataInfo = {};
    this.deleteDataInfo = {};
    this._init();
}

letterView_Comm.prototype = {
    _init : function() {

    },
    getNoteInfo : function(arg) {
        var _this = this;
        //ajax
        var serviceName = "getMessageDetail";
        var optionName = {
            "IN" : "messageInSeq",
            "OUT" : "messageOutSeq"
        }
        var options = {
            "key" : optionName[arg["송수신코드"]],
            "value" : arg["코드"]
        }
        console.log(options);
        //options[optionName[arg["송수신코드"]]] = arg["코드"];
        var objJson = new MJson();
        var cm = new ConnectionManager();
        objJson.putPub(MJson.PUB.SID, "MG001");
        objJson.putPub(MJson.PUB.SERVICENAME, serviceName);
        objJson.putClient(MJson.CLIENT.USERID, document.globalObj.LOGIN_DATA.userId);
        objJson.putParameter(options["key"], options["value"]);

        cm.requestGet(objJson.getJsonString(), function(ret) {

            var res = {
                "결과코드" : ret["msp"]["contents"]["serviceResult"],
                "메시지" : ret["msp"]["result"]["msg"],
                "결과값" : {}
            }

            var items = ret["msp"]["contents"]["items"];
            console.log(items);
            if(items) {
                var obj = items;
                var cName = "";
                if(obj["senderType"] == "C") {
                    cName = obj["club"]["clubName"];
                }

                var userid = "";
                var d = "";
                var t = "";
                switch(arg["송수신코드"]) {
                    case "IN":
                        userid = obj["senderUserId"];
                        d = String(obj["sendDate"]) + "";
                        t = String(obj["sendTime"]) + "";
                        break;
                    case "OUT":
                        userid = obj["recUserId"];
                        d = obj["recDate"] ? String(obj["recDate"]) : "";
                        t = obj["recTime"] ? String(obj["recTime"]) : "";
                        break;
                }
                setTimeout(function() {
                    _this.noteInfo = {
                        "동호회명" : cName,
                        "회원정보" : {
                            "아이디" : userid
                        },
                        "날짜" : d.substr(0, 4) + "-" + d.substr(4, 2) + "-" + d.substr(6, 2),
                        "시간" : t.substr(0, 2) + ":" + t.substr(2, 2),
                        "내용" : obj["messageBody"],
                        "송수신코드" : arg["송수신코드"],
                        "보관여부" : arg["보관여부"]
                    };

                    $(_this).trigger("finishNoteInfo");
                }, 500);
            }
            console.log("===========================");

        }, function($err) {
            console.log("errod >>>>>>>>>");
            console.log($err);
        });
    },
    getNoteData : function() {
        return this.noteInfo;
    },
    getUserData : function() {
        return this.userInfo;
    },
    getSaveInfoData : function() {
        return this.saveDataInfo;
    },
    getDeleteInfoData : function() {
        return this.deleteDataInfo;
    },
    getUserInfo : function(arg) {
        
        var _this = this;
        var userID = arg;
        var serviceName = 'getUserInfo';
        var objJson = new MJson();
        var cm = new ConnectionManager();
        objJson.putPub(MJson.PUB.SID, "US001");
        objJson.putPub(MJson.PUB.SERVICENAME, serviceName);
        objJson.putClient(MJson.CLIENT.USERID, document.globalObj.LOGIN_DATA.userId);
        objJson.putParameter("userId", userID);

        cm.requestGet(objJson.getJsonString(), function(ret) {
            console.log(ret)
            var res = {
                "결과코드" : ret["msp"]["contents"]["serviceResult"],
                "메시지" : ret["msp"]["result"]["msg"]
            }

            var items = ret["msp"]["contents"]["items"];
            var info = {};
            console.log(ret);
            if(items) {
                var obj = items;

                var objSex = {
                    "M" : "남성",
                    "F" : "여성"
                }
                info = {
                    "아이디" : obj["userId"],
                    "이메일" : obj["email"],
                    "닉네임" : obj["nickname"],
                    "성별코드" : obj["sex"],
                    "성별" : objSex[obj["sex"]],
                    "나이코드" : obj["age"] ? obj["age"] : "",
                    "나이대" : "",
                    "지역코드" : obj["region"] ? obj["region"] : "",
                    "지역명" : "",
                    "핸디" : obj["handi"] ? obj["handi"] : 0,
                    "평균타수" : obj["everage"] ? obj["everage"] : 0,
                    "이미지" : obj["path"] + obj["saveFileName"] ? obj["path"] + obj["saveFileName"] : ""
                }
                setTimeout(function() {
                    _this.userInfo = {
                        "결과값" : res,
                        "유저정보" : info
                    }
                    $(_this).trigger('finishUserInfo');
                }, 500)
            }
        }, function($err) {
            console.log("errod >>>>>>>>>");
            console.log($err);
        });
    },
  
    noteDelete : function(arg) {
       var _this = this;
        var serviceName = "deleteMessage";
        var optionName = {
            "IN": "messageInSeq"
            , "OUT": "messageOutSeq"
        }
        var objJson = new MJson();
        var cm = new ConnectionManager();
        var options = {
            "key" : optionName[arg["송수신코드"]],
            "value" : arg["코드"] , 
        }
        if(arg["보관여부"] != "Y") {
            options["inOutFlag"] = arg["송수신코드"];
            var options2 = {
                "key" : "inOutFlag",
                "value" : arg["송수신코드"] , 
            }
            objJson.putParameter(options2["key"], options2["value"]);
        }
        
        objJson.putPub(MJson.PUB.SID, "MG001");
        objJson.putPub(MJson.PUB.SERVICENAME, serviceName);
        objJson.putClient(MJson.CLIENT.USERID, document.globalObj.LOGIN_DATA.userId);
        objJson.putParameter(options["key"], options["value"]);
        cm.requestGet(objJson.getJsonString(), function(ret) {
            console.log(ret);
            
            setTimeout(function() {
                _this.deleteDataInfo =  {
                    "결과코드": ret["msp"]["contents"]["serviceResult"]
                    , "메시지":  ret["msp"]['result']['msg']
                }
                $(_this).trigger('finishDeleteLetter');
            }, 500)
            
        }, function($err) {
            console.log("errod >>>>>>>>>");
            console.log($err);
        });
       
    },
    noteSave : function(arg) {
        var _this = this;
        var serviceName = "saveMessage";
        var optionName = {
            "IN": "messageInSeq"
            , "OUT": "messageOutSeq"
        }
        var options = {
            "key" : optionName[arg["송수신코드"]],
            "value" : arg["코드"]
        }
        var objJson = new MJson();
        var cm = new ConnectionManager();
        objJson.putPub(MJson.PUB.SID, "MG001");
        objJson.putPub(MJson.PUB.SERVICENAME, serviceName);
        objJson.putClient(MJson.CLIENT.USERID, document.globalObj.LOGIN_DATA.userId);
        objJson.putParameter(options["key"], options["value"]);
        cm.requestGet(objJson.getJsonString(), function(ret) {
            console.log(ret)
            
            setTimeout(function() {
                _this.saveDataInfo =  {
                    "결과코드": ret["msp"]["contents"]["serviceResult"]
                    , "메시지":  ret["msp"]['result']['msg']
                }
                $(_this).trigger('finishSaveLetter');
            }, 500)
            
        }, function($err) {
            console.log("errod >>>>>>>>>");
            console.log($err);
        });
    }
}

/*
 * view
 */
function letterView_View() {
    this.infoData = null;
    // 쪽지 데이터
    this.HTMLDom = null;
    this._init();
}

letterView_View.prototype = {
    _init : function() {
        var $layer = $("section#letter_view>section");
        this.HTMLDom = {
            "$tileName" : $layer.find('#letter_view_titleName'),
            "$dTitle" : $layer.find('#letter_write_dTitle'),
            "$nick" : $layer.find('#letter_view_nick'),
            "$date" : $layer.find('#letter_view_date'),
            "$txt" : $layer.find('#letter_view_txt'),
            "$answer" : $layer.find('#answer_letter_view'),
            "$save" : $layer.find("#save_letter_view"),
            "$delete" : $layer.find("#delete_letter_view")
        };
        this.setInfo({
            "동호회명" : "",
            "날짜" : "",
            "시간" : "",
            "내용" : ""
        });
        
        this.showTime().hide();
        this.buttonHide();
    },
    buttonHide : function() {
        console.log(this.HTMLDom["$answer"]);
        console.log(this.HTMLDom["$save"]);
        console.log(this.HTMLDom["$delete"]);
        
        
        this.HTMLDom["$answer"].hide();
        this.HTMLDom["$save"].hide();
        this.HTMLDom["$delete"].hide();
    },
    spinStart : function() {
        $.mobile.showPageLoadingMsg();
    },
    spinEnd : function() {
        $.mobile.hidePageLoadingMsg();
    },
    showTime : function() {
        return $("section#letter_view>section");
    },
    display : function() {
        var titleName = {
            "IN" : "보낸사람",
            "OUT" : "받는사람"
        }

        var dTitleName = {
            "IN" : "발송일",
            "OUT" : "수신일"
        }
        this.HTMLDom["$tileName"].text(titleName[this.infoData["송수신코드"]]);
        this.HTMLDom["$dTitle"].text(dTitleName[this.infoData["송수신코드"]]);
        this.HTMLDom["$date"].text(this.infoData["날짜"] + " " + this.infoData["시간"]);
        this.HTMLDom["$txt"].text(this.infoData["내용"]);

    },
    setInfo : function(thisData) {
        this.infoData = thisData;
        this.display();
    },
    setMemberInfo : function(thisData) {
        this.infoData["회원정보"] = thisData;
        console.log(">>>>>>>>>>>>>>>>>>>>>>>");
        console.log(this.infoData);
        this.displayMember();
    },
    displayMember : function() {
        var _this = this;
        this.HTMLDom["$nick"].text(_this.infoData["회원정보"]["유저정보"]["닉네임"]);
        this.showTime().show();
        
        this.HTMLDom["$delete"].show();
        if(this.infoData["보관여부"] != "Y")     this.HTMLDom["$save"].show();
        if(this.infoData["송수신코드"] == "IN") this.HTMLDom["$answer"].show();
        $('[data-role="controlgroup"]').controlgroup('refresh' , true);
        this.spinEnd();    
    }
     , finishNoteSave : function(ret){
         this.spinEnd();
         if(ret["결과코드"] != "00000") {
            alert(ret["메시지"]);
            return;
        }
         alert("쪽지를 보관하였습니다.");
         //쪽지 보관 완료 후 이동 페이지 작성  
         
     } 
    , finishNoteDelete: function(ret){
        this.spinEnd();
        if(ret["결과코드"] != "00000") {
            alert(ret["메시지"]);
            return;
        }
        alert("쪽지를 삭제하였습니다.");
         //쪽지 삭제 완료 후 이동 페이지 작성  
    }
}

